package com.geping.etl.common.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;

import ch.qos.logback.core.util.EnvUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.geping.etl.common.dto.UserDto;
import com.geping.etl.common.entity.*;
import com.geping.etl.common.repository.Report_InfoRepository;
import com.geping.etl.common.security.pwd.PwdPolicyServiceDispatcher;
import com.geping.etl.common.service.*;
import com.geping.etl.common.util.BusinessResponse;
import com.geping.etl.common.util.Constants;
import com.geping.etl.utils.EnvUitl;
import com.geping.etl.utils.HttpUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


import com.geping.etl.common.util.VariableUtils;
import com.geping.etl.utils.sm3.SM3PrintUtil;

import static java.util.stream.Collectors.*;

@RestController
public class LoginController {

    @Autowired
    private Sys_UserService sys_UserService;
    @Autowired
    private Sys_UserAndOrgDepartmentService sod;
    @Autowired
    private LogsService ls;
    @Autowired
    private Sys_SubjectService sss;
    @Autowired
    private Sys_MenuService sms;
    @Autowired
    private Sys_Auth_Role_ResourceService sarrs;

    @Autowired
    private Report_InfoService report_infoService;
    @Autowired
    private Sys_OrgService sys_orgService;

    @Autowired
    private Sys_DepartmentService sys_departmentService;

    @Resource
    private Report_InfoService reportInfoService;

    @Autowired
    private PasswordUpdatePolicyService passwordUpdatePolicyService;

    @Value("${maxTime}")
    private Integer maxTime;

    @Autowired
    private Sys_UserAndOrgDepartmentService sys_UserAndOrgDepartmentService;

//	@Autowired
//	private DAreaCodeService as;
//	@Autowired
//	private DCurrencyCodeService cs;

    private Sys_UserAndOrgDepartment sys_User;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //访问登录页面
    @RequestMapping(value = "/loginUi", method = RequestMethod.GET)
    public ModelAndView loginUi(HttpServletRequest request) {
//		BaseCodeInit.getBaseCodeResource(as, cs);
        ModelAndView model = new ModelAndView();
        Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");

        if (sys_User != null) {
		/*	String ip = "192.168.1.110";
			if(ip == null || sys_User.getIp() == null || sys_User.getIp().equals("")) {
				model.addObject("message","ip为空,请联系管理员");
				model.setViewName("common/login");
			}else if(!ip.equals(sys_User.getIp())){
				model.addObject("message","该用户登录ip地址与绑定ip地址不符");
				model.setViewName("common/login");
			}else {*/
            sys_UserService.updateLastLoginDate(sdf.format(new Date()), sys_User.getId());
            List<Sys_Subject> subjectList = sss.findSubjectByUserId(sys_User.getId());

           /* if (!Constants.BX_SYN_USER_ON.equals(EnvUitl.props.getProperty("beixian.user"))) {
                try {
                    int days = (int) ((new Date().getTime() - sdf.parse(sys_User.getLastmodifydate()).getTime()) / (1000 * 60 * 60 * 24));
                    if (days >= passwordUpdatePolicyService.getUpdateIntervalDays() || sys_User.getIsfirstlogin().equals("Y")) {
                        request.setAttribute("needEditPwd", "Y");
                    } else {
                        request.setAttribute("needEditPwd", "N");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }*/

            request.getSession().setAttribute("sys_User", sys_User);
            request.setAttribute("sys_User", sys_User);
            model.addObject("subjectList", subjectList);
            model.setViewName("common/main");
            /*}*/
        } else {
            model.setViewName("common/login");
        }

        return model;
    }


    //处理登录请求
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        request.getSession().setAttribute("updateIntervalDays", String.valueOf(passwordUpdatePolicyService.getUpdateIntervalDays()));
        //添加密码修改提示
        request.getSession().setAttribute("pwdTip", PwdPolicyServiceDispatcher.getPwdPolicyService(EnvUitl.props.getProperty(Constants.PWD_POLICY_CUSTOMER)).getPwdPolicy().getTip());
        ModelAndView model = new ModelAndView();
        Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
        String bxSyn = EnvUitl.props.getProperty("beixian.user");
        request.getSession().setAttribute("bxSyn", bxSyn);
        Map<String, String> orgIdMapName = sys_orgService.findAllSysOrg().stream().collect(Collectors.toMap(Sys_Org::getOrgId, Sys_Org::getOrgName, (k1, k2) -> k2));
        request.getSession().setAttribute("orgIdMapName", orgIdMapName);
        String user_more_org = EnvUitl.props.getProperty("user_more_org");
        String user_more_dept = EnvUitl.props.getProperty("user_more_dept");
        if (StringUtils.isNotBlank(user_more_org) && "on".equals(user_more_org))
            request.getSession().setAttribute("user_more_org", user_more_org);
        else request.getSession().setAttribute("user_more_org", "off");

        if (StringUtils.isNotBlank(user_more_dept) && "on".equals(user_more_dept))
            request.getSession().setAttribute("user_more_dept", user_more_dept);
        else request.getSession().setAttribute("user_more_dept", "off");

        //设置台湾银行项目开关判断
        String taiwanUser = EnvUitl.props.getProperty("taiwan.user");
        request.getSession().setAttribute("taiwanUser", taiwanUser);

        //设置华晨east2项目开关判断
        String east2Huachen = EnvUitl.props.getProperty("east2.huachen");
        request.getSession().setAttribute("east2Huachen", east2Huachen);

        //设置外管局项目开关判断
        String waihuiUser = EnvUitl.props.getProperty("waihui.user");
        request.getSession().setAttribute("waihuiUser", waihuiUser);
        if (sys_User != null) {
          /*  String ip = "192.168.1.110";
            if (ip == null || sys_User.getIp() == null || sys_User.getIp().equals("")) {
                model.addObject("message", "ip为空,请联系管理员");
                model.setViewName("common/login");
            } else if (!ip.equals(sys_User.getIp())) {
                model.addObject("message", "该用户登录ip地址与绑定ip地址不符");
                model.setViewName("common/login");
            } else {*/
            sys_UserService.updateLastLoginDate(sdf.format(new Date()), sys_User.getId());
            List<Sys_Subject> subjectList = sss.findSubjectByUserId(sys_User.getId());

           /* if (!Constants.BX_SYN_USER_ON.equals(EnvUitl.props.getProperty("beixian.user"))) {
                try {
                    int days = (int) ((new Date().getTime() - sdf.parse(sys_User.getLastmodifydate()).getTime()) / (1000 * 60 * 60 * 24));
                    if (days >= passwordUpdatePolicyService.getUpdateIntervalDays() || sys_User.getIsfirstlogin().equals("Y")) {
                        request.setAttribute("needEditPwd", "Y");
                    } else {
                        request.setAttribute("needEditPwd", "N");
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }*/

            request.getSession().setAttribute("sys_User", sys_User);
            request.setAttribute("sys_User", sys_User);
            model.addObject("subjectList", subjectList);
            model.setViewName("common/main");
            /*  }*/
        } else {
            String loginId = request.getParameter("loginId");
            String password = request.getParameter("password");
            password = password.toUpperCase();

            sys_User = sod.findSysUserLogin(loginId, password);
            if (sys_User != null) {
                //String ip = getIp(request);
				/*String ip = "192.168.1.110";
				if(ip == null || sys_User.getIp() == null || sys_User.getIp().equals("")) {
					model.addObject("message","ip为空,请联系管理员");
					model.setViewName("common/login");
				}else if(!ip.equals(sys_User.getIp())){
					model.addObject("message","该用户登录ip地址与绑定ip地址不符");
					model.setViewName("common/login");
				}else {*/
                sys_UserService.updateLastLoginDate(sdf.format(new Date()), sys_User.getId());
                List<Sys_Subject> subjectList = sss.findSubjectByUserId(sys_User.getId());
                request.getSession().setAttribute("subjectId", subjectList);
                sys_UserService.updateTime("0", loginId);
                //将登录信息加到日志中
                Logs logs = new Logs();
                logs.setLoginId(sys_User.getLoginid());
                logs.setLogContent(sys_User.getLoginid() + "登录系统");
                logs.setLogDate(sdf.format(new Date()));
                logs.setLogOrgCode(sys_User.getOrgid());
                logs.setLogType("登录");
                ls.save(logs);   //添加日志信息

				/*	if(!Constants.BX_SYN_USER_ON.equals(EnvUitl.props.getProperty("beixian.user"))) {
						try {
							int days = (int) ((new Date().getTime() - sdf.parse(sys_User.getLastmodifydate()).getTime()) / (1000 * 60 * 60 * 24));
							if (days >= passwordUpdatePolicyService.getUpdateIntervalDays() || sys_User.getIsfirstlogin().equals("Y")) {
								request.setAttribute("needEditPwd", "Y");
							} else {
								request.setAttribute("needEditPwd", "N");
							}
						} catch (ParseException e) {
							e.printStackTrace();
						}
					}*/

                request.getSession().setAttribute("sys_User", sys_User);
                request.setAttribute("sys_User", sys_User);

                // 获取session
                HttpSession session = request.getSession();
                // 是否显示ip输入框，有配置则隐藏
                String showUserIp = EnvUitl.props.getProperty("showUserIp");
                if (StringUtils.isBlank(showUserIp)) {
                    showUserIp = "";
                }
                session.setAttribute("showUserIp", showUserIp);
                model.addObject("subjectList", subjectList);
                model.setViewName("common/main");
                /*}*/
            } else {
                Logs logs = new Logs();
                logs.setLogContent("登录账号或密码错误");
                Sys_User sys_user = sys_UserService.getOneByLoginId(loginId);
                model.addObject("message", "登录账号或密码错误！");
				/*if (sys_user!=null){
					if(StringUtils.isBlank(sys_user.getFailNums())){
						sys_user.setFailNums("0");
					}
					Integer times = Integer.parseInt(sys_user.getFailNums());
					times = ++times;
					sys_UserService.updateTime(times.toString(),loginId);
					if (times>=6 || sys_user.getIsLocked().equals("Y")){
						model.addObject("message","登录账号已被锁定！");
						logs.setLogContent("登录账号已被锁定");
						sys_UserService.agreenLock(sys_user.getId(),"Y");
					}
				}*/
                //将登录信息加到日志中

                logs.setLoginId(loginId);

                logs.setLogDate(sdf.format(new Date()));
                logs.setLogOrgCode("");
                logs.setLogType("登录");
                ls.save(logs);   //添加日志信息
                model.setViewName("common/login");
            }
        }
        return model;
    }

/*	private void pwdPolicyInit(ModelAndView model, Sys_UserAndOrgDepartment sys_User) {
		model.addObject("currentCustomer",EnvUitl.props.getProperty(Constants.PWD_POLICY_CUSTOMER));
		model.addObject("sysUserJson", JSON.toJSONString(new UserDto(sys_User.getId(),sys_User.getLoginid())));
	}*/


    //访问主页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("text/html");
        response.setContentType("text/plain; charset=utf-8");
        ModelAndView model = new ModelAndView();
        Sys_UserAndOrgDepartment sys_User = (Sys_UserAndOrgDepartment) request.getSession().getAttribute("sys_User");
        String userId = request.getParameter("userId");
        String subjectId = request.getParameter("subjectId");//系统编号
        String subjectName = "";//系统名称
        if (request.getParameter("subjectName") != null) {
            subjectName = URLDecoder.decode(request.getParameter("subjectName"), "UTF-8");
        }
        String systemUrl = EnvUitl.props.getProperty(subjectId) != null ? EnvUitl.props.getProperty(subjectId) : "";

        //通过用户id和系统id获取所有权限数据
        List<Sys_Auth_Role_Resource> resourceList = sarrs.findResourceByRoleAndSubject(userId, subjectId).stream().filter(Objects::nonNull).collect(Collectors.toList());
        Sys_Auth_Role_Resource resource = null;
        TreeSet<Sys_Auth_Role_Resource> menuSet = new TreeSet<Sys_Auth_Role_Resource>();  //菜单集
        TreeSet<Sys_Auth_Role_Resource> reportSet = new TreeSet<Sys_Auth_Role_Resource>();  //报表集
        TreeSet<Sys_Auth_Role_Resource> operateReportSet = new TreeSet<Sys_Auth_Role_Resource>();  //操作按钮集

        List<Sys_Menu> menuListAll = new ArrayList<>();
        List<Sys_Menu> oneLevelMenu = new ArrayList<Sys_Menu>();//一级菜单
        List<Sys_Menu> twoLevelMenu = new ArrayList<Sys_Menu>();//二级菜单
        List<Sys_Menu> threeLevelMenu = new ArrayList<Sys_Menu>();//三级菜单
        for (int i = 0; i < resourceList.size(); i++) {
            resource = resourceList.get(i);
            /*if(!String.valueOf(resource).equals("null")){*/
            if (resource.getResType().equals("Menu")) {
                menuSet.add(resource);
            } else if (resource.getResType().equals("Report")) {
                reportSet.add(resource);
            } else if (resource.getResType().equals("OperateReport")) {
                operateReportSet.add(resource);
            } else {

            }
            /*}*/
        }


        String orgId = sys_User.getOrgid();
        List<Sys_Org> sysOrgs = sys_orgService.selectOrgById(orgId);
        VariableUtils vu = new VariableUtils();
        vu.setReportSet(reportSet);
        vu.setOperateReportSet(operateReportSet);

        if (CollectionUtils.isNotEmpty(sysOrgs)) {
            vu.setLicenseNumber(sysOrgs.get(0).getLicenseNumber());
            vu.setBankNumber(sysOrgs.get(0).getBankBankNumber());
        }
        Specification specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("subjectId"), subjectId));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        List<Report_Info> reportInfos = reportInfoService.findAllBySome(specification);


        //服务健康检查
        if (StringUtils.isNotBlank(systemUrl)
                && !subjectId.equals("30")) {
            String result = HttpUtil.getRequestAddHeaderAndRetry(systemUrl + Constants.HEALTH, null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (!BusinessResponse.SUCCESS.getCode().equals(jsonObject.get(Constants.CODE))) {
                model.addObject("message", subjectName + "服务未启动");
                model.setViewName("common/error");
            }
        }

        if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))
                && Constants.SYSTEM_PERSON_BANK_PROJECT.equals(subjectId)) {
            //只供个人银行项目使用
            sys_UserAndOrgDepartmentService.synUserInfoToPersonBank();
        }

        if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))
                && Constants.SYSTEM_CRS_PROJECT.equals(subjectId)) {
            sys_UserAndOrgDepartmentService.synUserInfoToCrs();
        }

//		/**
//		 * 针对企业征信和个人征信查询接口
//		 */
//		for(Sys_Auth_Role_Resource btResources : operateReportSet) {
//			if((subjectId.equals("4") || subjectId.equals("5")) && (btResources.getSubjectId().equals("4") || btResources.getSubjectId().equals("5"))) {
//				if(btResources.getResType().equals("OperateReport")) {
//					if(btResources.getResValue().equals("CHECK")) {
//						vu.setRole("checker");
//						break;
//					}
//
//					if(btResources.getResValue().equals("IMPORT") || btResources.getResValue().equals("ADD") || btResources.getResValue().equals("EDIT") || btResources.getResValue().equals("CHECKOUT")) {
//						vu.setRole("maker");
//						break;
//					}
//				}
//			}
//		 }


//		/**
//		 * 如果是汽车金融east，赋一些值给全局变量
//		 */
//		if(subjectId.equals("8")) {
//			vu.setLoginId(sys_User.getLoginid());
//			vu.setOrgId(sys_User.getOrgid());
//			vu.setOrgName(sys_User.getOrgname());
//			vu.setOrgInsideCode(sys_User.getOrginsidecode());
//			vu.setLicenseNumber(sys_User.getLicensenumber());
//
//			if(operateReportSet != null){
//		          if(!operateReportSet.isEmpty()){
//		        	  Iterator<Sys_Auth_Role_Resource> it = operateReportSet.iterator();
//		        	  int makerNum = 0;
//	        		  int checkerNum = 0;
//		        	  while(it.hasNext()){
//		        		  Sys_Auth_Role_Resource operatesource = it.next();
//		        		  if(operatesource.getResType().equals("OperateReport")) {
//		        			  if(operatesource.getResValue().equals("ADD_REPORT")){
//			                	  makerNum = makerNum + 1;
//			                  }else if(operatesource.getResValue().equals("EDIT_REPORT")){
//			                	  makerNum = makerNum + 1;
//			                  }else if(operatesource.getResValue().equals("DELETE_REPORT")){
//			                	  makerNum = makerNum + 1;
//			                  }else if(operatesource.getResValue().equals("EXAMINE_REPORT")){
//			                	  checkerNum = checkerNum + 1;
//			                  }else if(operatesource.getResValue().equals("IMPORT_REPORT")){
//			                	  makerNum = makerNum + 1;
//			                  }else if(operatesource.getResValue().equals("GENERATE_MESSAGE")){
//			                	  makerNum = makerNum + 1;
//			                  }else if(operatesource.getResValue().equals("REPORT_SUBMIT")){
//			                	  makerNum = makerNum + 1;
//			                  }else{
//
//			                  }
//		        		  }
//
//		                  if(checkerNum > 0 && makerNum == 0){
//		                	  vu.setRoleStyle("checker");
//		                  }
//		                  if(checkerNum == 0 && makerNum > 0){
//		                	  vu.setRoleStyle("maker");
//		                  }
//		                  if(checkerNum > 0 && makerNum > 0){
//		                	  vu.setRoleStyle("makerAndChecker");
//		                  }
//		    	  }
//	           }
//		   }
//		}


        menuListAll = sms.getMenuBySubjectId(subjectId).stream().filter(Objects::nonNull).collect(Collectors.toList());
        StringBuffer menuHtml = new StringBuffer();
        for (Sys_Auth_Role_Resource sr : menuSet) {
            for (Sys_Menu sm : menuListAll) {
                /*if(!String.valueOf(sm).equals("null")){*/
                if (sm.getId() == Integer.parseInt(sr.getResId())) {
					/*if(sm.getPmenuid() == null || sm.getPmenuid().equals("")) {
						oneLevelMenu.add(sm);
					}else {
						twoLevelMenu.add(sm);
					}*/

                    if (sm.getOrderNum().equals("0")) {
                        oneLevelMenu.add(sm);
                    } else if (Integer.parseInt(sm.getOrderNum()) > 0 && sm.getOrderNum().length() <= 2) {
                        twoLevelMenu.add(sm);
                    } else if (sm.getOrderNum().length() == 3) {
                        threeLevelMenu.add(sm);
                    }
                    continue;
                }
                /*}*/
            }
        }

        for (int i = 0; i < oneLevelMenu.size(); i++) {
            menuHtml.append("<div title=\"" + oneLevelMenu.get(i).getName() + "\" style=\"overflow:auto;padding:10px;\">\r\n");
            menuHtml.append("<ul class=\"easyui-tree\">\r\n");
            for (int j = 0; j < twoLevelMenu.size(); j++) {
                if (oneLevelMenu.get(i).getId().intValue() == Integer.valueOf(twoLevelMenu.get(j).getPmenuid()).intValue()) {
                    if (Integer.parseInt(twoLevelMenu.get(j).getOrderNum()) > 0 && twoLevelMenu.get(j).getUrl().equals("#")) {   //判断是否有三级菜单，如果有
                        menuHtml.append("<li data-options=\"state:'closed'\">\r\n");
                        menuHtml.append("<span>" + twoLevelMenu.get(j).getName() + "</span>\r\n");
                        menuHtml.append("<ul\r\n>");
                        for (int k = 0; k < threeLevelMenu.size(); k++) {
                            if (twoLevelMenu.get(j).getId().intValue() == Integer.valueOf(threeLevelMenu.get(k).getPmenuid()).intValue()) {
                                menuHtml.append("<li data-options=\"iconCls:'" + threeLevelMenu.get(k).getIcon() + "'\">\r\n");
                                menuHtml.append("<a onclick=\"addTab('" + threeLevelMenu.get(k).getName() + "','" + systemUrl + threeLevelMenu.get(k).getUrl() + "')\"><span>" + threeLevelMenu.get(k).getName() + "</span></a>\r\n");
                                menuHtml.append("</li>\r\n");
                            }
                        }
                        menuHtml.append("</ul>\r\n");
                        menuHtml.append("</li>\r\n");
                    } else {
                        menuHtml.append("<li data-options=\"iconCls:'" + twoLevelMenu.get(j).getIcon() + "'\">\r\n");
                        menuHtml.append("<a onclick=\"addTab('" + twoLevelMenu.get(j).getName() + "','" + systemUrl + twoLevelMenu.get(j).getUrl() + "')\"><span>" + twoLevelMenu.get(j).getName() + "</span></a>\r\n");
                        menuHtml.append("</li>\r\n");
                    }
                }
            }
            menuHtml.append("</ul>\r\n");
            menuHtml.append("</div>\r\n");
        }

        //瑞福德多机构判断
        if ("on".equals(request.getSession().getAttribute("user_more_org")) && Integer.valueOf(subjectId) > 2) {
            if (StringUtils.isNotBlank(sys_User.getEnddate())) {
                Map<String, String> sIdMapOrgId = JSON.parseObject(sys_User.getEnddate(), Map.class);
                if (null != sIdMapOrgId.get(subjectId)) {
                    String oId = sIdMapOrgId.get(subjectId);
                    List<Sys_Org> sys_orgs = sys_orgService.findAllSysOrg().stream().filter(sys_org -> sys_org.getEnabled().equalsIgnoreCase("Y")).collect(Collectors.toList());
                    Map<String, String> idMapName = sys_orgs.stream().collect(Collectors.toMap(Sys_Org::getOrgId, Sys_Org::getOrgName, (k1, k2) -> k2));
                    String sName = idMapName.get(oId);
                    sys_User.setOrgid(oId);
                    sys_User.setOrgname(sName);
                } else {
                    throw new RuntimeException("您未被分配该系统的机构！请先申请分配该系统的对应机构！");
                }
            } else {
                throw new RuntimeException("未查询到该用户多机构信息！");
            }
//			List<Sys_Org> sys_orgs = sys_orgService.findAllSysOrg().stream().filter(sys_org -> sys_org.getEnabled().equalsIgnoreCase("Y")).collect(Collectors.toList());
//			final Map<String, String> idMapName = sys_orgs.stream().collect(Collectors.toMap(Sys_Org::getOrgId, Sys_Org::getOrgName, (k1, k2) -> k2));
//			Map<Integer, List<String>> orgidMap = sys_orgs.stream().collect(groupingBy(Sys_Org::getOrgLayer,mapping(Sys_Org::getOrgId,toCollection(ArrayList::new))));
//			final AtomicInteger integer = new AtomicInteger(0);
//			if (null != orgidMap.get(Integer.valueOf(subjectId))) {
//				final List<String> allOrgs = orgidMap.get(Integer.valueOf(subjectId));
//				if (StringUtils.isNotBlank(sys_User.getEnddate())) {
//					List<String> hasOrgs = JSON.parseObject(sys_User.getEnddate(),List.class);
//					hasOrgs.forEach(s -> {
//						if (allOrgs.contains(s)) {
//							sys_User.setOrgid(s);
//							sys_User.setOrgname(idMapName.get(s));
//							integer.incrementAndGet();
//						}
//					});
//				}
//			} else {
//				throw new RuntimeException("未查询到该用户多机构信息！");
//			}
//			if (integer.get() == 0) throw new RuntimeException("您未被分配该系统的机构！请先申请分配该系统的对应机构！");
        }
        //多部门判断
        if ("on".equals(request.getSession().getAttribute("user_more_dept")) && Integer.valueOf(subjectId) > 2) {
            if (StringUtils.isNotBlank(sys_User.getSystemdept())) {
                Map<String, String> sIdMapDeptId1 = JSON.parseObject(sys_User.getSystemdept(), Map.class);
                if (null != sIdMapDeptId1.get(subjectId)) {
                    String dept = sIdMapDeptId1.get(subjectId);
                    sys_User.setIsdept(dept);
                } else {
                    throw new RuntimeException("您未被分配该系统的部门！请先申请分配该系统的对应部门！");
                }
            } else {
                throw new RuntimeException("未查询到该用户多部门信息！");
            }
        }
        request.getSession().setAttribute("resources", resourceList);
        request.getSession().setAttribute("vu", vu);
        //台湾银行，需要修改部门id，截取前七位
        if (Constants.TAIWAN_BANK_USER_ON.equals(EnvUitl.props.getProperty("taiwan.user"))) {
            Sys_UserAndOrgDepartmentVo sysUserVo = new Sys_UserAndOrgDepartmentVo();
            BeanUtils.copyProperties(sys_User, sysUserVo);
            sysUserVo.setDepartid(sysUserVo.getDepartid().substring(0, 7));
            request.getSession().setAttribute("sysUser", sysUserVo);
        } else {
            request.getSession().setAttribute("sysUser", sys_User);
        }
        request.getSession().setAttribute("sysOrgs", sysOrgs);
        request.getSession().setAttribute("loginId", sys_User.getLoginid());
        if ("30".equals(subjectId)) {
            request.getSession().setAttribute("url", systemUrl + Constants.SYSTEM_1104_URL);
        } else {
            request.getSession().setAttribute("url", systemUrl + Constants.SYSTEM_USER_INFO_URL);
        }
        model.addObject("menuHtml", menuHtml.toString());
        model.addObject("subjectName", subjectName);
        request.setAttribute("subjectId", subjectId);
        String east2Huachen = (String) request.getSession().getAttribute("east2Huachen");
        List<Report_Info> roleList = report_infoService.getReportBySubjectId(subjectId, east2Huachen);
        Map<String, List<Report_Info>> map = roleList.stream().collect(groupingBy(Report_Info::getCode));
        if ("8".equals(subjectId)) {
            Map<String, Map<String, Map<String, List<String>>>> targetMap = new HashMap<>();
            Set<String> set = map.keySet();
            for (String s : set) {
                List<Report_Info> list = map.get(s);
                if (null != list && list.size() > 0) {
                    if (StringUtils.isNotBlank(list.get(0).getUpdateTime())) {
                        String groupInfo = list.get(0).getUpdateTime();
                        Map<String, Map<String, List<String>>> tempMap = JSON.parseObject(groupInfo, Map.class);
                        targetMap.put(s, tempMap);
                    }
                }
            }
            String groupStr = JSON.toJSONString(targetMap);
            model.addObject("groupMap", groupStr);
        } else {
            Map<String, Map<String, List<String>>> targetMap = new HashMap<>();
            Set<String> set = map.keySet();
            for (String s : set) {
                List<Report_Info> list = map.get(s);
                if (null != list && list.size() > 0) {
                    if (StringUtils.isNotBlank(list.get(0).getUpdateTime())) {
                        String groupInfo = list.get(0).getUpdateTime();
                        Map<String, List<String>> tempMap = JSON.parseObject(groupInfo, Map.class);
                        targetMap.put(s, tempMap);
                    }
                }
            }
            String groupStr = JSON.toJSONString(targetMap);
            model.addObject("groupMap", groupStr);
        }
        List<Sys_User> allUsers = sys_UserService.findAllSysUser();
        Map<String, String> loginIdDeptMap = allUsers.stream().collect(Collectors.toMap(Sys_User::getLoginId, Sys_User::getDepartId, (k1, k2) -> k2));
        allUsers.forEach(sys_user -> {
            if ("N".equals(sys_user.getIsDept())) {
                loginIdDeptMap.put(sys_user.getLoginId(), "noDeptId");
            }
        });
        String loginIdDeptStr = JSON.toJSONString(loginIdDeptMap);
        model.addObject("loginIdDeptMap", loginIdDeptStr);
        if (StringUtils.isNotBlank(systemUrl)) {
            vu.setReportInfoList(reportInfos);
            vu.setOneSysMenuList(oneLevelMenu);
            vu.setTwoSysMenuList(twoLevelMenu);
            vu.setThreeSysMenuList(threeLevelMenu);
            model.setViewName("common/redirect");
        } else {
            model.setViewName("common/index");
        }


        return model;
    }

    private void clearContext(List<Sys_Auth_Role_Resource> resourceList, TreeSet<Sys_Auth_Role_Resource> menuSet, List<Sys_Menu> menuListAll, List<Sys_Menu> oneLevelMenu, List<Sys_Menu> twoLevelMenu) {
        if (resourceList != null) {
            resourceList.clear();
            resourceList = null;
        }

        if (menuSet != null) {
            menuSet.clear();
            menuSet = null;
        }

	   /* if(reportSet != null) {
	    	reportSet.clear();
	    	reportSet = null;
	    }

	    if(operateReportSet != null) {
	    	operateReportSet.clear();
	    	operateReportSet = null;
	    }*/

        if (menuListAll != null) {
            menuListAll.clear();
            menuListAll = null;
        }

        if (oneLevelMenu != null) {
            oneLevelMenu.clear();
            oneLevelMenu = null;
        }

        if (twoLevelMenu != null) {
            twoLevelMenu.clear();
            twoLevelMenu = null;
        }
    }


    //访问首页
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public ModelAndView home() {
        ModelAndView model = new ModelAndView();
        model.setViewName("common/home");
        return model;
    }


    //安全退出
    @RequestMapping(value = "/userOut", method = RequestMethod.GET)
    public ModelAndView userOut(HttpServletRequest request) {
        ModelAndView model = new ModelAndView();
        request.getSession().removeAttribute("sys_User");  //将用户信息从session中删除
        model.setViewName("common/login");
        return model;
    }

    //获取ip地址
    public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (null == ip || 0 == ip.length() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
